using UnityEngine;
using System;

#if UNITY_OPENHARMONY

/// <summary>
/// 应用内支付模块管理类
/// 提供OpenHarmony平台应用内支付解决方案，包括商品购买和订单修复功能
/// </summary>
public class IapKitManager
{
    /// <summary>
    /// OpenHarmony JS对象，用于与原生应用内支付模块交互
    /// </summary>
    private static OpenHarmonyJSObject m_iapKitManagerObj = null;

    /// <summary>
    /// 应用内支付回调事件，用于接收支付操作结果
    /// </summary>
    private static Action<string, string> m_iapKitManagerAction = null;

    /// <summary>
    /// OpenHarmony JS回调对象
    /// </summary>
    private static OpenHarmonyJSCallback m_iapKitManagerCallback = null;

    /// <summary>
    /// 初始化应用内支付模块
    /// </summary>
    /// <param name="callback">支付操作结果回调，参数为(类型, 数据)</param>
    public static void Init(Action<string, string> callback)
    {
        m_iapKitManagerCallback = new OpenHarmonyJSCallback(IapKitManagerCallback);

        var IapKitManager = new OpenHarmonyJSClass("IapKitManager");
        m_iapKitManagerObj = IapKitManager.CallStatic<OpenHarmonyJSObject>("getInstance");
        Debug.Log($"IapKitManager:Init IapKitManagerObj={m_iapKitManagerObj}");

        m_iapKitManagerAction = callback;
    }

    /// <summary>
    /// 处理来自OpenHarmony的应用内支付回调
    /// </summary>
    /// <param name="args">回调参数，第一个参数为类型，第二个参数为数据</param>
    /// <returns>无返回值</returns>
    private static object IapKitManagerCallback(params OpenHarmonyJSObject[] args)
    {
        Debug.Log("IapKitManagerCallback: " + args.Length);
        if (args.Length > 0)
        {
            Debug.Log("IapKitManagerCallback type: " + args[0].As<string>());
            Debug.Log("IapKitManagerCallback data: " + args[1].As<string>());
            m_iapKitManagerAction?.Invoke(args[0].As<string>(), args[1].As<string>());
        }
        return null;
    }

    /// <summary>
    /// 发起商品购买
    /// </summary>
    /// <param name="productType">商品类型</param>
    /// <param name="productId">商品ID</param>
    public static void PayOrder(int productType, string productId)
    {
        m_iapKitManagerObj.Call("payOrder", productType, productId, m_iapKitManagerCallback);
    }

    /// <summary>
    /// 修复订单
    /// 用于处理未完成的订单或异常状态的订单
    /// </summary>
    public static void FixOrders()
    {
        m_iapKitManagerObj.Call("fixOrders", m_iapKitManagerCallback);
    }
}

#endif